/****
 * * @author wangming
 * 2020/3/17
 * 文件说明：请求类型分装
 *****/
import axios from './axios.js';
import { Message } from 'element-ui';
import {hosts} from './hosts'

const generateSignData = (data = {}) => {
    return data;
};

function urlStrToObj(url) {
    var obj = new Object();
    if (url.indexOf('?') != -1) {
        //判断？后面是否有字符
        var strTemp = url.split('?'); //以？符号分离
        obj.url = strTemp[0];
        var strs = strTemp[1].split('&'); //以&符号分离
        for (var i = 0; i < strs.length; i++) {
            //decodeURI：将字符解码
            //decodeURIComponent：加密
            obj[strs[i].split('=')[0]] = decodeURI(strs[i].split('=')[1]);
        }
        obj.flag = true;
    } else obj.flag = false;
    return obj;
}
export class Axios {
    constructor(baseUrl = hosts.front_api){
        this.baseUrl = baseUrl;
    }
    request(url,method,data={}){
        url = this.baseUrl+url;
        return new Promise((resolve, reject) => {
            let paramobj = {
                method: method,
                url: url,
            }
            method=='get'?paramobj['params']=data:paramobj['data'] = data;
            axios(paramobj).then(
                res => {
                    if (res.status&&res.data.code == 200)
                        resolve(res.data);
                    else
                        Message.error(res.data.message);
                        reject(res.data);
                },
                err => {
                    Message.error(err);
                    reject(err);
                }
            );
        });
    }
    get(url, data = {}){
        var urlObj = urlStrToObj(url);
        if (urlObj.flag) {
            url = urlObj.url;
            delete urlObj.url;
            delete urlObj.flag;
            data = Object.assign(data, urlObj);
        }
        generateSignData(data);
        return this.request(url,'get',data)
    }
    post(url, data = {}){
        generateSignData(data);
        return this.request(url,'post',data)
    }
    put(url, data = {}){
        generateSignData(data);
        return this.request(url,'put',data)
    }
    delete(url, data = {}){
        var urlObj = urlStrToObj(url);
        if (urlObj.flag) {
            url = urlObj.url;
            delete urlObj.url;
            delete urlObj.flag;
            data = Object.assign(data, urlObj);
        }
        generateSignData(data);
        return this.request(url,'delete',data)
    }
}
const _axios = new Axios()

export default _axios
